package org.elanfox.intellicommunity.data.base.base;

import org.elanfox.intellicommunity.common.utils.BeanUtilsExt;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Map;

/**
 * @author wm
 */
public class SqlDataReader {
    private Map<String, Object> map;

    public SqlDataReader(Map<String, Object> map) {
        this.map = map;
    }

    private Object getObject(String field) {
        return this.map.get(field);
    }

    public Integer getInteger(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return 0;
        }
        return new Integer(obj.toString());
    }

    public Long getLong(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return 0L;
        }
        return new Long(obj.toString());
    }

    public String getString(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return "";
        }
        return obj.toString();
    }

    public BigDecimal getBigDecimal(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return BigDecimal.ZERO;
        }
        return new BigDecimal(obj.toString());
    }

    public Boolean getBoolean(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return false;
        }
        return new Boolean(obj.toString());
    }

    public LocalDate getLocalDate(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return null;
        }
        return (LocalDate) obj;
    }

    public String getLocalDateTimeStr(String field) {
        Object obj = this.getObject(field);
        if (obj == null) {
            return null;
        }
        Timestamp ts = Timestamp.valueOf(obj.toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(ts);
    }

    public <T> T convert(Class<T> beanClass) {
        return (T) BeanUtilsExt.mapConvertToObject(this.map, beanClass.getClass());
    }
}